import React, { useState } from 'react';
import { Avatar, Button, Comment, Input, Modal } from 'antd';
import Cookies from 'js-cookie';
import { useTranslation } from 'react-i18next';

import { submitCommentApi, deleteCommentApi } from '@src/services/company';
import dobleModalConfig from '@src/utils/dobleModalConfig';

import styles from './styles.module.less';

const { TextArea } = Input;

const defaultProfile = '/img/placeholder.jpg';

const ExampleComment = ({ children, data, onRefresh }) => {
  const { t } = useTranslation();

  const [replyModalVisible, setReplyModalVisible] = useState(false);
  const [replyValue, setReplyValue] = useState('');
  const [submitReplyLoading, setSubmitReplyLoading] = useState(false);

  const onSubmitReply = async () => {
    if (!replyValue.trim()) return;

    setSubmitReplyLoading(true);

    const res = await submitCommentApi({
      business_server_id: data.business_server_id,
      content: replyValue,
      parent_id: data.comment_id
    });

    setSubmitReplyLoading(false);
    if (!res) return;

    onCancelReply();
    onRefresh();
  }

  const onDeleteComment = async () => {
    const configFlag = await dobleModalConfig(t('Are you sure you want to delete this comment?'));
    if (!configFlag) return;

    const res = await deleteCommentApi({
      comment_id: data.comment_id
    });

    if(!res) return;
    onRefresh();
  }

  const onCancelReply = () => {
    setReplyModalVisible(false);
    setReplyValue('');
  }

  return (
    <div className={styles.example_comment}>
      <Comment
        actions={[
          <span key="comment-nested-reply-to" onClick={() => setReplyModalVisible(true)}>{t('Reply')}</span>,
          Number(data.user.user_id) === Number(Cookies.get('ai-user-id')) ? (
            <span onClick={onDeleteComment}>{t('Delete')}</span>
          ) : null
        ]}
        author={<a>{data.user.email}</a>}
        avatar={<Avatar src={defaultProfile} alt="" />}
        content={
          <p>
            {data.content}
          </p>
        }
      >
        {children}
      </Comment>
      <Modal
        open={replyModalVisible}
        footer={null}
        onCancel={onCancelReply}
      >
        <div className={styles.example_comment_reply_modal}>
          <div className={styles.title}>{t('Reply')}@{data.user?.email}</div>
          <TextArea
            placeholder={t('Post your reply')}
            value={replyValue}
            onChange={(e) => {
              setReplyValue(e.target.value);
            }}
          />
          <div className={styles.footer_box}>
            <Button type="primary" loading={submitReplyLoading} onClick={onSubmitReply}>{t('Reply')}</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default ExampleComment;
